#include "firstlevelwidget.h"

FirstLevelWidget::FirstLevelWidget()
{
    initTextData("./data/branch.txt");
    updateUI();
}

int FirstLevelWidget::initTextData(const char *fileName)
{
    std::fstream file;
    int posX = 100;
    int posY = 130;
    int perWidth = 135;
    int perHeight = 60;
    int spaceWidth = 30;
    int spaceHeight = 15;
    int line=0; //行
    int column = 0;//列
    int cnt=0;

    file.open(fileName,std::ios_base::in);
    if(!file.is_open())
    {
        std::cout<<"open "<<fileName<<"error "<<strerror(errno)<<std::endl;
        return -1;
    }
    while(!file.eof())
    {
        char buf[1024] = {0};
        file.getline(buf,sizeof(buf));

        //eg: 儿科=儿科综合/小儿内科/小儿外科/新生儿科/儿童营养保健科

        //切割一级学科   eg:儿科
        std::string text = std::string(buf);
        std::string value = text.substr(0,text.find("/"));

        m_list.push_back(Button(value.c_str(),
                                   posX+(spaceWidth+perWidth)*column,
                                   posY+(spaceHeight+perHeight)*line,
                                   perWidth,
                                   perHeight));

        if(++cnt % 4 == 0)
            line++;

        column = (column+1) %4;

        std::cout<<value<<std::endl;
    }

    file.close();
    return 0;
}

void FirstLevelWidget::updateUI()
{
    if(m_list.empty())
        return ;

    Bmp b1("./res/firstlevel.bmp");
    b1.show();

    std::list<Button>::iterator it;
    for(it=m_list.begin(); it!=m_list.end(); it++)
    {
        std::cout<<it->text()<<"\t"<<it->x()<<"\t"<<it->y()<<std::endl;
        CFont::instance()->show(it->text(),36,110,40,CFont::WHITE,CFont::BLACK,it->x(),it->y());
    }
}

bool FirstLevelWidget::selectItem(int &x, int &y)
{
    std::list<Button>::iterator it;
    for(it=m_list.begin(); it!=m_list.end(); it++)
    {
        //从容器中找到点击的学科
        if(x >= it->x() && x<=it->x()+it->width()
           && y>=it->y()&& y<=it->y()+it->height())
        {
            m_cItem = it->text();
            return true;
        }
    }

    return  false;
}

std::string FirstLevelWidget::currentItem()
{
    return this->m_cItem;
}

int FirstLevelWidget::exec()
{
    int state;
    bool exitFlag = false;

    while(1)
    {
        Touch touch;
        int x,y;
        touch.wait(x,y);

        if(x>=100 && x<730 && y>=130 && y<=190) //点击一级学科
            state = 1;
        else if(x>650 && x<800 && y>410 && y<480) //返回
            exitFlag = true;

        switch (state) {
            case 1:
                exitFlag = selectItem(x,y);
                break;
        }

        if(exitFlag)
            break;
    }
}
